/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package com.stip.server.da;

import com.stip.server.entities.Dorm;
import com.stip.server.entities.UsersInfo;
import com.stip.server.entities.UsersMain;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author BlueBerry
 */
@Stateless
@LocalBean
public class UserInfoDA {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @PersistenceContext 
    EntityManager em;
    public UsersInfo findUserInfoByID(String uid){
    UsersInfo usersInfo=em.find(UsersInfo.class, uid);
    return  usersInfo;
    }
    public String createUserInfo(String uid ,String email,String qq,String phone,String abstracts,Integer dorm){
    UsersInfo usersInfo=new UsersInfo();    
    usersInfo.setUid(uid);
    usersInfo.setEmail(email);
    usersInfo.setQq(qq);
    usersInfo.setAbstracts(abstracts);
    usersInfo.setPhone(phone);
    UsersMain usermain=em.find(UsersMain.class, uid);
    usersInfo.setUsersMain(usermain);
    Dorm dorm1=em.find(Dorm.class, dorm);
    usersInfo.setDorm(dorm1);
    em.persist(usersInfo);
        try {
            em.flush();
            return  usersInfo.getUid();
        } catch (EntityExistsException e) {
            return  null;
        }
    
    }
    public Boolean editUserInfo(String uid ,String email,String qq,String phone,String abstracts,Integer dorm){
    UsersInfo usersInfo=em.find(UsersInfo.class, uid);
        if (usersInfo!=null) {
             if (email==null) {
           usersInfo.setEmail(usersInfo.getEmail());
        } else {
            usersInfo.setEmail(email);
        }
        if (qq==null) {
            usersInfo.setQq(usersInfo.getQq());
        } else {
            usersInfo.setQq(qq);
        }
        if (phone==null) {
            usersInfo.setPhone(usersInfo.getPhone());
        } else {
            usersInfo.setPhone(phone);
        }
        if (abstracts==null) {
            usersInfo.setAbstracts(usersInfo.getAbstracts());
        } else {
            usersInfo.setAbstracts(abstracts);
        }
        if (dorm==null) {
            usersInfo.setDorm(usersInfo.getDorm());
        } else {
            usersInfo.setDorm(em.find(Dorm.class, dorm));
        }
        em.merge(usersInfo);
        return  true;
        } else {
           return  false; 
        }
       
    }        
    public Boolean deleteUserInfo(String uid){
    UsersInfo usersInfo=em.find(UsersInfo.class, uid);
        if (usersInfo!=null) {
            em.remove(usersInfo);
            return  true;
        } else {
            return  false;
        }
    }
}
